package org.test.client.ui.component.btn;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.AbstractButton;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;

import org.test.client.ui.MainApplication;
import org.test.client.ui.top.TopPanel;
import org.test.client.ui.util.UIConstants;

public class MouseInListener extends MouseAdapter {
	private AbstractButton thisBtn = null;
	private Color rollover = null;
	private Color pressedColor = null;
	private boolean isToggle = false;
	
	public MouseInListener(AbstractButton btn,Color rollover){
		this(btn,rollover,null);
	}
	
	public MouseInListener(AbstractButton btn,Color rollover, Color pressedColor){
		thisBtn = btn;
		this.rollover = rollover;
		this.pressedColor = pressedColor;
		if(thisBtn instanceof JToggleButton){
			isToggle = true;
		}
	}
	
	@Override
	public void mouseEntered(MouseEvent e) {
		super.mouseEntered(e);
		if(rollover != null){
			thisBtn.setContentAreaFilled(true);
			thisBtn.setBackground(rollover);
		}
		thisBtn.setCursor(new Cursor(Cursor.HAND_CURSOR));
	}

	@Override
	public void mouseExited(MouseEvent e) {
		boolean selected = thisBtn.isSelected();
		if(!selected){
			thisBtn.setContentAreaFilled(false);
			thisBtn.setBackground(null);
			thisBtn.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
		} 
	}

//	@Override
//	public void mousePressed(MouseEvent mouseevent) {
//		if(pressedColor == null){
//			return; 
//		}
//		thisBtn.setContentAreaFilled(true);
//		thisBtn.setBackground(pressedColor);
//	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		
		if (thisBtn instanceof DropdownToggleBtn) {
			
			DropdownToggleBtn tmpBtn = (DropdownToggleBtn) thisBtn;
			JPopupMenu popMenu = tmpBtn.getPopMenu();
			if(popMenu != null && !popMenu.isVisible()){
				
				int x = 0;
				int y = tmpBtn.getY()+UIConstants.topBtnHeigth;
				Dimension d = popMenu.getPreferredSize();
				
				Point p = new Point(x+d.width,y);
				SwingUtilities.convertPointToScreen(p, tmpBtn);
				MainApplication frame = tmpBtn.getTp().getMainFrame();
				int frameRight = frame.getX()+frame.getWidth();
				if( frameRight -10 < p.x){
					x = tmpBtn.getWidth() - d.width;
				}
				
				popMenu.show(tmpBtn, x, y);
			}
		}
	}
	
}
